package studio.raptor.dispatcher.common.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * @author jack
 * @since 1.0
 */
public class FileLoader {

  public static String readLocalFile(String filename) throws IOException {
    return FileLoader.readFile(filename);
  }

  public static Properties loadLocalProps(String filePath) throws IOException {
    return FileLoader.loadProps(filePath);
  }

  private static String readFile(String filename) throws IOException {
    String content = null;
    InputStream in = null;
    BufferedReader br = null;
    try {
      StringBuilder sb = new StringBuilder();
      in = FileLoader.class.getClassLoader().getResourceAsStream(filename);
      if (null == in) {
        throw new IOException(filename + " is not found");
      }
      br = new BufferedReader(new InputStreamReader(in, Charset.forName("utf-8")));
      while ((content = br.readLine()) != null) {
        sb.append(content).append("\n");
      }
      content = sb.toString();
    } finally {
      try {
        if (br != null) {
          br.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return content;
  }

  private static Properties loadProps(String filePath) throws IOException {
    Properties props = new Properties();
    InputStream ips = FileLoader.class.getClassLoader().getResourceAsStream(filePath);
    if(null == ips) {
      return null;
    }
    try {
      props.load(ips);
    } finally {
      try {
        ips.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return props;
  }

}
